package com.runfast.waimai.web.controller;

import com.runfast.common.dao.IMapper;
import com.runfast.common.dao.model.RunfastCuseraddress;
import com.runfast.common.dao.model.RunfastDeliverCost;
import com.runfast.common.service.RunfastCuseraddressService;
import com.runfast.common.service.RunfastDeliverCostService;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.paotui.entity.DeliveryCost;
import com.runfast.waimai.dao.mapper.RunfastBusinessMapper;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.entity.CartItem;
import com.runfast.waimai.entity.CartItemKey;
import com.runfast.waimai.entity.OptionIdPair;
import com.runfast.waimai.service.*;
import com.runfast.waimai.web.dto.BusinessDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 外卖订单接口
 */
@RestController("userWmOrderController")
@RequestMapping(value = "/api/user/wm/order", headers = "token")
public class OrderController {

    @Autowired
    private RunfastGoodsSellRecordService goodsSellRecordService;


    @Autowired
    private RunfastBusinessService businessService;

    @Autowired
    private RunfastCuseraddressService cuseraddressService;

    @Autowired
    private RunfastActivityService activityService;


    @Autowired
    private RunfastGoodsSellService goodsSellService;

    @Autowired
    private RunfastDeliverCostService deliverCostService;

    @Autowired
    private RunfastFullLessService fullLessService;


    /**
     * 获取订单分页列表
     *
     * @param pageable 分页请求参数
     * @return
     */
    @PostMapping("/list")
    public Result<List<RunfastGoodsSellRecord>> list(@PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        return Result.ok("");
    }


    /**
     * 确认订单
     *
     * @param order 请求参数
     * @return
     */
    @PostMapping(value = "/confirm")
    public Result confirm(@ModelAttribute RunfastGoodsSellRecord order, @RequestHeader String token) {

//        order.setCuserId(SessionContext.getCurrentUser().getId());
        Integer userId = TokenUtil.getUserId(token);
        return Result.ok("");

    }

    /**
     * 取消订单
     *
     * @param orderId 订单Id
     * @return
     */
    @PostMapping("/cancel")
    public Result cancel(@RequestParam Integer orderId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        return Result.ok("");

    }


    /**
     * 删除订单
     *
     * @param businessId 商户id
     * @param orderId    订单id
     * @param token
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestParam int businessId, @RequestParam int orderId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        return Result.ok("");

    }

    /**
     * 再来一单
     *
     * @param orderId
     * @param token
     * @return
     */
    @PostMapping("/recur")
    public Result recur(@RequestParam int orderId, @RequestHeader String token) {

        return Result.ok("");

    }

    /**
     * 获取订单状态列表
     *
     * @param orderId 订单id
     * @param token
     * @return
     */
    @PostMapping("/status")
    public Result status(@RequestParam int orderId, @RequestHeader String token) {


        return Result.ok("");

    }


    /**
     * 获取订单详情
     *
     * @param orderId
     * @param token
     * @return
     */
    @PostMapping("/detail")
    public Result<RunfastGoodsSellRecord> detail(@RequestParam int orderId, @RequestHeader String token) {


        return Result.ok("");

    }


    /**
     * 根据用户购物车，地址或者可用红包获取确认订单页面信息（用户地址和红包可以为null）
     *
     * @param businessId  商户id
     * @param toAddressId 选择的用户地址id
     * @param redPacketId 红包id
     * @param token
     * @return
     */
    @PostMapping("/fillIn")
    public Result fillIn(@RequestParam double userLng, @RequestParam double userLat, @RequestParam Integer businessId, @RequestBody List<CartItem> cart, @RequestParam(required = false) Integer toAddressId, @RequestParam(required = false) Integer redPacketId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        RunfastBusiness business = businessService.selectByPrimaryKey(businessId);
        if (business == null) return Result.fail(ResultCode.BUSINESS_NOT_EXIST);
        Integer agentId = business.getAgentId();

        /**
         * 校验null
         */
        List<Integer> optionIdListForCheck = new ArrayList<>();
        for (CartItem cartItem : cart) {

            Integer num = cartItem.getNum();
            if (num == null || num < 1) return Result.fail(ResultCode.FAIL, "数量必须大于0");

            CartItemKey key = cartItem.getKey();
            Integer goodsId = key.getGoodsId();
            if (goodsId == null) return Result.fail(ResultCode.FAIL, "商品id不能为null");
            Integer standarId = key.getStandarId();
            if (standarId == null) return Result.fail(ResultCode.FAIL, "规格id不能为null");

            List<OptionIdPair> optionIdPairListForCheck = key.getOptionIdPairList();


            List<Integer> subOptionIdListForCheck = new ArrayList<>();
            if (optionIdPairListForCheck != null && !optionIdPairListForCheck.isEmpty()) {
                for (OptionIdPair pair : optionIdPairListForCheck) {
                    if (pair.getOptionId() != null) {
                        optionIdListForCheck.add(pair.getOptionId());
                    } else {
                        return Result.fail(ResultCode.FAIL, "属性不能为null");
                    }
                    if (pair.getSubOptionId() != null) {
                        subOptionIdListForCheck.add(pair.getSubOptionId());
                    } else {
                        return Result.fail(ResultCode.FAIL, "子选项不能为null");
                    }
                }
            }

        }

        /**
         * 校验规格
         */

        List<Map<String, Object>> goodsStandarList = goodsSellService.checkGoodsWithStandar(businessId, cart);
        if (goodsStandarList.size() != cart.size()) {//数据库规格记录和规格参数不匹配
            return Result.fail(ResultCode.STANDARD_NOT_EXIST, "该商品已修改,请重新下单");
        }

        /**
         * 校验属性
         */

        List<Map<String, Object>> goodsOptionList = goodsSellService.checkGoodsWithOption(businessId, cart);
        if (goodsOptionList.size() != optionIdListForCheck.size()) {
            return Result.fail(ResultCode.SUB_OPTION_NOT_EXIST, "该商品已修改,请重新下单");
        }

        Map<String, Object> fillInMap = new HashMap<>();


        fillInMap.put("businessImg", business.getImgPath());
        fillInMap.put("businessName", business.getName());
        fillInMap.put("isDeliver", business.getIsDeliver());

        BusinessDto businessDto = null;
        if (toAddressId != null) {

            RunfastCuseraddress toAddress = cuseraddressService.selectByPrimaryKey(toAddressId);
            Double toLng = Double.valueOf(toAddress.getLongitude());
            Double toLat = Double.valueOf(toAddress.getLatitude());

            businessDto = businessService.detailWithDistance(businessId, toLng, toLat);
        } else {
            businessDto = businessService.detailWithDistance(businessId, userLng, userLat);
        }

        /**
         * 计算商家配送费和配送时间
         */

        RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentId);

        int distance = ((Double) businessDto.getDistance()).intValue();//以米为单位
        Integer deliver = (Integer) businessDto.getIsDeliver();
        boolean isDeliver = deliver != null && deliver == 1;


        int deliveryDuration = 0;//配送时间（分）
        Double deliveryFee = 0d;//配送费
        if (isDeliver) {
            //自配送

            BigDecimal busshowps = (BigDecimal) businessDto.getBusshowps();
            if (busshowps == null || busshowps.compareTo(BigDecimal.valueOf(0)) == -1) {
                busshowps = BigDecimal.valueOf(0);
            }
            deliveryFee = busshowps.doubleValue();

            Integer packTime = (Integer) businessDto.getPackTime();
            packTime = packTime == null ? 10 : packTime;
            Integer distributionTime = (Integer) businessDto.getDistributionTime();
            distributionTime = distributionTime == null ? 10 : distributionTime;
            deliveryDuration = packTime + distributionTime;

        } else {
            //代理商配送
            DeliveryCost deliveryCost = deliverCostService.getDeliveryCost(toAddressId == null ? null : distance, null, defaultDeliveryTemplate);

            deliveryFee = deliveryCost.getDeliveryFee() / 100d;

            Double speed = defaultDeliveryTemplate.getSpeed();
            int distributionTime = (int) Math.ceil(distance * 10 * speed / 1000);
            Integer packTime = (Integer) businessDto.getPackTime();
            packTime = packTime == null ? 10 : packTime;
            deliveryDuration = packTime + distributionTime;

        }
        deliveryDuration = deliveryDuration < 25 ? 25 : deliveryDuration;//少于25分钟按照25分钟计算
        fillInMap.put("deliveryFee", deliveryFee);
        fillInMap.put("deliveryDuration", deliveryDuration);


        List<CartItem> cartItemViewList = new ArrayList<>();


        Double cartPrice = 0d;//购物车条目原总价



        Map<Integer, Map<String, Object>> sharedOffActivityMap = new HashMap<>();//同享打折特价活动购物车优惠力度map
        Map<Integer, Map<String, Object>> notSharedOffActivityMap = new HashMap<>();//不同享打折特价活动购物车优惠力度map
        for (CartItem cartItem : cart) {
            cartItemViewList.add(cartItem);

            Integer num = cartItem.getNum();

            CartItemKey cartItemKey = cartItem.getKey();
            Integer goodsId = cartItemKey.getGoodsId();
            Integer standarId = cartItemKey.getStandarId();


            for (Map<String, Object> goodsStandar : goodsStandarList) {

                Integer gsId = (Integer) goodsStandar.get("gs_id");
                Integer gssId = (Integer) goodsStandar.get("gss_id");

                if (goodsId == gsId.intValue() && standarId == gssId.intValue()) {


                    String gsName = (String) goodsStandar.get("gs_name");
                    String gsImgPath = (String) goodsStandar.get("gs_imgPath");
                    String gsMiniImgPath = (String) goodsStandar.get("gs_mini_imgPath");

                    String gssName = (String) goodsStandar.get("gss_name");
                    Double gssPrice = (Double) goodsStandar.get("gss_price");

                    Integer aId = (Integer) goodsStandar.get("a_id");
                    Integer aPtype = (Integer) goodsStandar.get("a_ptype");
                    Boolean aShared = (Boolean) goodsStandar.get("a_shared");

                    Integer aIsLimited = (Integer) goodsStandar.get("a_is_limited");
                    Integer aLimitNum = (Integer) goodsStandar.get("a_limit_num");

                    Double aDiscount = (Double) goodsStandar.get("a_discount");
                    Double aDisprice = (Double) goodsStandar.get("a_disprice");


                    goodsStandar.put("numBy", num);//保存购买数量，后面会用到

                    cartPrice += gssPrice * num;
                    if (aPtype != null && (aPtype == 2 || aPtype == 4)) {//打折或者特价
                        aDisprice = aDisprice > gssPrice ? gssPrice : aDisprice;


                        Map<String, Object> offActivity = sharedOffActivityMap.get(aId);
                        Double offAmount = Double.valueOf(0d);
                        if (offActivity == null) {
                            offActivity = new HashMap<>();
                            offActivity.put("activityType", aPtype);
                            offActivity.put("offAmount", offAmount);
                        }

                        offAmount = (Double) offActivity.get("offAmount");

                        RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(Calendar.HOUR_OF_DAY,0);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                        Date start = calendar.getTime();
                        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)+1);
                        Date end = calendar.getTime();
                        goodsSellRecordExample.or().andUserIdEqualTo(userId).andCreateTimeBetween(start, end);
                        List<RunfastGoodsSellRecord> goodsSellRecords = goodsSellRecordService.selectByExample(goodsSellRecordExample);

                        if(goodsSellRecords.size()>2){//按原价

                            //？？？？

                        }else{//当天的订单数不超过2

                            if (aIsLimited == null || aIsLimited == 1) {//该活动限购(? 当前订单or当天)
                                aLimitNum = aLimitNum == null || aLimitNum < 1 ? 1 : aLimitNum;
                                if (num > aLimitNum) {//超出限购数量
                                    offAmount += (gssPrice - aDisprice) * aLimitNum;
                                } else {//未超出限购数量
                                    offAmount += (gssPrice - aDisprice) * num;
                                }
                            } else {//不限购
                                offAmount += (gssPrice - aDisprice) * num;
                            }

                            offActivity.put("offAmount", offAmount);
                            if (aShared != null && aShared) {
                                sharedOffActivityMap.put(aId, offActivity);
                            } else {
                                notSharedOffActivityMap.put(aId, offActivity);
                            }


                        }



                    }


                }

            }


        }





        Double offAmount = 0d;
        List<Object> validActivityList = new ArrayList<>();
        /**
         * 计算红包活动
         */
        Map<RunfastActivity, Double> activityOffMap = new HashMap<>();//保存活动优惠的额度
        if (redPacketId != null) {//选择了红包


            RunfastActivity redActivity = activityService.selectByPrimaryKey(redPacketId);
            Boolean shared = redActivity.getShared();
            if (shared == null || !shared) {//红包与其他活动不同享，则不考虑(除了免配送费和新用户活动)其他活动


                //获取免运费,新用户活动,红包活动,有即享受，不参与最大优惠力度算法
                List<Object> alwaysSharedActivityList = getAlwaysSharedActivityList(businessId, deliveryFee);
                alwaysSharedActivityList.add(redActivity);

                Map<String, Object> shareMap = getSharedMap(userId, agentId, cartPrice, deliveryFee,alwaysSharedActivityList);
                offAmount = (Double) shareMap.get("sharedOffAmount");
                validActivityList = (List<Object>) shareMap.get("sharedValidActivityList");


            } else {//红包与其他活动同享,加入同享活动列表，参与同享计算

                Map<String, Object> preferMap = getPreferMap(businessId, userId, agentId, deliveryFee, cartPrice, sharedOffActivityMap, notSharedOffActivityMap, redActivity);

                offAmount = (Double) preferMap.get("offAmount");
                validActivityList = (List<Object>) preferMap.get("validActivityList");


            }
        } else {
            Map<String, Object> preferMap = getPreferMap(businessId, userId, agentId, deliveryFee, cartPrice, sharedOffActivityMap, notSharedOffActivityMap, null);

            offAmount = (Double) preferMap.get("offAmount");
            validActivityList = (List<Object>) preferMap.get("validActivityList");
        }


        /**
         * 根据订单满足的活动重新计算购物车条目的打折和特价
         */
        for (CartItem cartItem : cart) {
            cartItemViewList.add(cartItem);

            Integer num = cartItem.getNum();

            CartItemKey cartItemKey = cartItem.getKey();
            Integer goodsId = cartItemKey.getGoodsId();
            Integer standarId = cartItemKey.getStandarId();


            for (Map<String, Object> goodsStandar : goodsStandarList) {

                Integer gsId = (Integer) goodsStandar.get("gs_id");
                Integer gssId = (Integer) goodsStandar.get("gss_id");

                if (goodsId == gsId.intValue() && standarId == gssId.intValue()) {


                    String gsName = (String) goodsStandar.get("gs_name");
                    String gsImgPath = (String) goodsStandar.get("gs_imgPath");
                    String gsMiniImgPath = (String) goodsStandar.get("gs_mini_imgPath");

                    String gssName = (String) goodsStandar.get("gss_name");
                    Double gssPrice = (Double) goodsStandar.get("gss_price");

                    Integer aId = (Integer) goodsStandar.get("a_id");
                    Integer aPtype = (Integer) goodsStandar.get("a_ptype");
                    Boolean aShared = (Boolean) goodsStandar.get("a_shared");

                    Integer aIsLimited = (Integer) goodsStandar.get("a_is_limited");
                    Integer aLimitNum = (Integer) goodsStandar.get("a_limit_num");

                    Double aDiscount = (Double) goodsStandar.get("a_discount");
                    Double aDisprice = (Double) goodsStandar.get("a_disprice");


                    StringBuilder goodsItemBuilder = new StringBuilder();
                    goodsItemBuilder.append(gssName);

                    for (Map<String, Object> goodsOption : goodsOptionList) {
                        Integer gsId1 = (Integer) goodsOption.get("gs_id");
                        if (gsId == gsId1.intValue()) {
                            String sName = (String) goodsStandar.get("s_name");//子选项名称

                            goodsItemBuilder.append("+" + sName);
                        }

                    }
                    cartItem.setStandarOptionName(goodsItemBuilder.toString());

                    cartItem.setActivityType(aPtype);
                    cartItem.setGoodsName(gsName);
                    cartItem.setGoodsImg(gsImgPath);


                    for (Object activity : validActivityList) {
                        if(activity instanceof Map.Entry){
                            Map.Entry offActivityAmountPair = (Map.Entry) activity;
                            Integer activityId = (Integer) offActivityAmountPair.getKey();
                            if(activityId== aId.intValue()){//该规格的特价或者打折活动，经过最大优惠力度计算是可以享受的
                                if (aIsLimited == null || aIsLimited == 1) {//该活动限购
                                    aLimitNum = aLimitNum == null || aLimitNum < 1 ? 1 : aLimitNum;
                                    if (num > aLimitNum) {
                                        cartItem.setPrice(gssPrice*aLimitNum);
                                        cartItem.setNum(aLimitNum);
                                        cartItem.setDisprice(aDisprice*aLimitNum);

                                        int exccedNum = aLimitNum - num;
                                        CartItem exceedCartItem = new CartItem();
                                        BeanUtils.copyProperties(cartItem, exceedCartItem);
                                        exceedCartItem.setNum(exccedNum);
                                        cartItem.setPrice(gssPrice*exccedNum);
                                        exceedCartItem.setActivityType(null);
                                        exceedCartItem.setDisprice(null);//超出原价购买
                                        cartItemViewList.add(exceedCartItem);
                                    } else {
                                        cartItem.setDisprice(aDisprice*aLimitNum);
                                    }

                                }else{
                                    cartItem.setDisprice(aDisprice*aLimitNum);
                                }
                            }
                        }
                    }


                }

            }


        }

        /**
         * 按购物车条目添加的时间降序
         */
        cartItemViewList.sort(new Comparator<CartItem>() {
            @Override
            public int compare(CartItem o1, CartItem o2) {
                return o1.getCreateTime().compareTo(o2.getCreateTime());
            }
        });


        return Result.ok("");


    }

    private Map<String, Object> getPreferMap(Integer businessId, Integer userId, Integer agentId, Double deliveryFee, Double cartPrice, Map<Integer, Map<String, Object>> sharedOffActivityMap, Map<Integer, Map<String, Object>> notSharedOffActivityMap, RunfastActivity redActivity) {
        List<Object> sharedActivityList = new ArrayList<>(); //同享的活动列表
        List<Object> notSharedActivityList = new ArrayList<>(); //不同享的活动列表
        sharedActivityList.addAll(sharedOffActivityMap.entrySet());
        notSharedActivityList.addAll(notSharedOffActivityMap.entrySet());
        Double offAmount;
        List<Object> validActivityList; /**
         * 满减活动
         */
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(1);

        //存在多个同类型的活动
        List<RunfastActivity> businessActivityList = activityService.findBusinessActivity(businessId, activityTypeList);


        for (RunfastActivity activity : businessActivityList) {
            Boolean shared1 = activity.getShared();
            if (shared1 != null && shared1) {//同享
                sharedActivityList.add(activity);
            } else {
                notSharedActivityList.add(activity);
            }

        }

        Map<String, Object> sharedMap = getSharedMap(userId, agentId, cartPrice, deliveryFee,sharedActivityList);
        Double sharedOffAmount = (Double) sharedMap.get("sharedOffAmount");
        List<Object> sharedValidActivityList = (List<Object>) sharedMap.get("sharedValidActivityList");

        Map<String, Object> notSharedMap = getNotSharedMap(userId, agentId, cartPrice, deliveryFee,notSharedActivityList);
        Double notSharedOffAmount = (Double) notSharedMap.get("notSharedOffAmount");
        List<Object> notSharedValidActivityList = (List<Object>) notSharedMap.get("notSharedValidActivityList");


        //获取免运费,新用户活动,红包活动,有即享受，不参与最大优惠力度算法
        List<Object> alwaysSharedActivityList = getAlwaysSharedActivityList(businessId, deliveryFee);
        if (redActivity != null) alwaysSharedActivityList.add(redActivity);
        Map<String, Object> alwaysharedMap = getSharedMap(userId, agentId, cartPrice, deliveryFee,alwaysSharedActivityList);
        Double alwaySharedOffAmount = (Double) alwaysharedMap.get("sharedOffAmount");
        List<Object> alwaySharedValidActivityList = (List<Object>) alwaysharedMap.get("sharedValidActivityList");


        if (sharedOffAmount > notSharedOffAmount) {
            offAmount = sharedOffAmount + alwaySharedOffAmount;
            sharedValidActivityList.addAll(alwaySharedValidActivityList);
            validActivityList = sharedValidActivityList;
        } else {
            offAmount = notSharedOffAmount + alwaySharedOffAmount;
            notSharedValidActivityList.addAll(alwaySharedValidActivityList);
            validActivityList = notSharedActivityList;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("offAmount", offAmount);
        map.put("validActivityList", validActivityList);

        return map;

    }


    /**
     * 获取免运费和新用户活动
     *
     * @param businessId
     * @param deliveryFee
     */
    private List<Object> getAlwaysSharedActivityList(Integer businessId, Double deliveryFee) {
        List<Object> alwaySharedActivityList = new ArrayList<>();
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(5);
        activityTypeList.add(7);
        activityTypeList.add(8);

        List<RunfastActivity> businessActivityList = activityService.findBusinessActivity(businessId, activityTypeList);

        /**
         * 同时存在全免运费和免部分运费，取优惠力度大的
         */
        Double deliveryOffAmount = 0d;//配送费优惠金额
        RunfastActivity deliveryActivity = null;//订单参与的免配送费活动
        for (RunfastActivity activity : businessActivityList) {
            Integer ptype = activity.getPtype();

            switch (ptype) {
                case 5:
                    if (deliveryFee > deliveryOffAmount) {
                        deliveryOffAmount = deliveryFee;
                        deliveryActivity = activity;
                    }
                    break;
                case 7:
                    Double less = activity.getLesss();
                    if (less > deliveryOffAmount) {
                        deliveryOffAmount = less;
                        deliveryActivity = activity;
                    }
                case 8:
                    alwaySharedActivityList.add(activity);//新用户活动
                    break;
            }

        }

        alwaySharedActivityList.add(deliveryActivity);

        return alwaySharedActivityList;
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> getSharedMap(Integer userId, Integer agentId, Double cartPrice, Double deliveryFee, List<Object> sharedActivityList) {
        Double shareOffAmount = 0d; //同享活动优惠总金额

        Map<String, Object> map = new HashMap<>();


        for (Object object : sharedActivityList) {
            //  活动类型：1满减  2打折3赠品4特价5满减免运费6优惠券7免部分配送费8新用户立减活动9首单立减活动10商户红包11下单返红包,(新用户立减即首单立减)

            Integer activityType = null;
            Integer activityId = null;

            RunfastActivity businessActivity = null;
            if (object instanceof RunfastActivity) {
                businessActivity = (RunfastActivity) object;
                activityType = businessActivity.getPtype();
                activityId = businessActivity.getId();
            } else {
                Map.Entry offActivityAmountPair = (Map.Entry) object;
                activityId = (Integer) offActivityAmountPair.getKey();
                Map<String, Object> offActivityMap = (Map<String, Object>) offActivityAmountPair.getValue();
                activityType = (Integer) offActivityMap.get("activityType");
            }


            switch (activityType) {
                case 1:

                    RunfastFullLessExample fullLessExample = new RunfastFullLessExample();
                    fullLessExample.or().andActivity_idEqualTo(activityId);
                    fullLessExample.setOrderByClause("full desc");//按照full降序

                    List<RunfastFullLess> fullLessList = fullLessService.selectByExampleWithPageable(fullLessExample, PageRequest.of(0, 5));//只取5个
                    for (RunfastFullLess fullLess : fullLessList) {
                        double full = fullLess.getFull() == null ? 0d : fullLess.getFull();
                        double less = fullLess.getLess() == null ? 0d : fullLess.getLess();
                        if (cartPrice >= full) {

                            shareOffAmount += less;
                            break;
                        }

                    }

                    break;

                case 2://打折
                case 4://特价
                    Map.Entry offActivityAmountPair = (Map.Entry) object;
                    activityId = (Integer) offActivityAmountPair.getKey();
                    Map<String, Object> offActivityMap = (Map<String, Object>) offActivityAmountPair.getValue();
                    shareOffAmount += (Double) offActivityMap.get("offAmount");
                    break;
                case 5://全免配送费

                    shareOffAmount += deliveryFee;

                    break;
                case 7://免部分配送费
                    shareOffAmount += businessActivity.getLesss();
                    break;
                case 8://新用户活动
                    RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();
                    goodsSellRecordExample.or().andUserIdEqualTo(userId).andAgentIdEqualTo(agentId);//代理商范围该用户是否下过单
                    List<RunfastGoodsSellRecord> goodsSellRecords = goodsSellRecordService.selectByExample(goodsSellRecordExample);
                    if (goodsSellRecords.isEmpty()) {//新用户下单
                        shareOffAmount += businessActivity.getLesss();
                    }
                    break;
                case 9:

                    break;
                case 10://商家红包
                case 11://返红包
                    shareOffAmount += businessActivity.getLesss();
                    break;

            }


        }

        map.put("sharedOffAmount", shareOffAmount);
        map.put("sharedValidActivityList", sharedActivityList);
        return map;
    }


    private Map<String, Object> getNotSharedMap(Integer userId, Integer agentId, Double cartPrice,Double deliveryFee, List<Object> notSharedActivityList) {
        Double notShareOffAmount = 0d; //不同享活动优惠金额（不同享活动由于互斥，只有一个活动参与最大优惠力度计算）

        Map<String, Object> map = new HashMap<>();
        Object notSharedValidActivity = null;//不同享活动列表中优惠力度最大的活动

        for (Object object : notSharedActivityList) {
            //  活动类型：1满减  2打折3赠品4特价5满减免运费6优惠券7免部分配送费8新用户立减活动9首单立减活动10商户红包11下单返红包,(新用户立减即首单立减)

            Integer activityType = null;
            Integer activityId = null;

            RunfastActivity businessActivity = null;
            if (object instanceof RunfastActivity) {
                businessActivity = (RunfastActivity) object;
                activityType = businessActivity.getPtype();
                activityId = businessActivity.getId();
            } else {
                Map.Entry offActivityAmountPair = (Map.Entry) object;
                activityId = (Integer) offActivityAmountPair.getKey();
                Map<String, Object> offActivityMap = (Map<String, Object>) offActivityAmountPair.getValue();
                activityType = (Integer) offActivityMap.get("activityType");
            }


            switch (activityType) {
                case 1:

                    RunfastFullLessExample fullLessExample = new RunfastFullLessExample();
                    fullLessExample.or().andActivity_idEqualTo(activityId);
                    fullLessExample.setOrderByClause("full desc");//按照full降序

                    List<RunfastFullLess> fullLessList = fullLessService.selectByExampleWithPageable(fullLessExample, PageRequest.of(0, 5));//只取5个
                    for (RunfastFullLess fullLess : fullLessList) {
                        double full = fullLess.getFull() == null ? 0d : fullLess.getFull();
                        double less = fullLess.getLess() == null ? 0d : fullLess.getLess();
                        if (cartPrice >= full) {

                            notShareOffAmount = less;
                            notSharedValidActivity = object;
                            break;
                        }

                    }

                    break;

                case 2://打折
                case 4://特价
                    Map.Entry offActivityAmountPair = (Map.Entry) object;
                    activityId = (Integer) offActivityAmountPair.getKey();
                    Map<String, Object> offActivityMap = (Map<String, Object>) offActivityAmountPair.getValue();
                    notShareOffAmount = (Double) offActivityMap.get("offAmount");
                    notSharedValidActivity = object;
                    break;
                case 5://全免配送费
                    Double deliveryCost = 0d;

                    notShareOffAmount = deliveryCost;
                    notSharedValidActivity = object;

                    break;
                case 7://免部分配送费
                    notShareOffAmount = businessActivity.getLesss();
                    notSharedValidActivity = object;
                    break;
                case 8://新用户活动
                    RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();
                    goodsSellRecordExample.or().andUserIdEqualTo(userId).andAgentIdEqualTo(agentId);//代理商范围该用户是否下过单
                    List<RunfastGoodsSellRecord> goodsSellRecords = goodsSellRecordService.selectByExample(goodsSellRecordExample);
                    if (goodsSellRecords.isEmpty()) {//新用户下单
                        notShareOffAmount = businessActivity.getLesss();
                        notSharedValidActivity = object;
                    }
                    break;
                case 9:
                    break;
                case 10://商家红包
                case 11://返红包
                    notShareOffAmount = businessActivity.getLesss();
                    notSharedValidActivity = object;
                    break;

            }


        }

        List<Object> notSharedValidActivityList = new ArrayList<>();
        notSharedValidActivityList.add(notSharedValidActivity);
        map.put("notSharedOffAmount", notShareOffAmount);
        map.put("notSharedValidActivityList", notSharedValidActivityList);
        return map;
    }

}
